package com.cpe.web.intercepter.separate.wechat;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.core.env.Environment;

import com.cpe.data.domain.member.Member;
import com.cpe.repository.mapper.member.MemberMapper;
import com.cpe.web.intercepter.base.AbstractInterceptor;
import com.google.common.collect.Maps;
import com.sql.data.domain.user.UserRespCode;
import com.util.https.HttpsUtil;
import com.wechat.api.URLPool;
import com.wechat.data.WebAccessToken;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Login4WechatInterceptor extends AbstractInterceptor {

	private Environment env;

	private MemberMapper memberMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 1.跳过排除的URI
		String mapping = request.getPathInfo();
		log.info("mapping=" + mapping);
		if (excludedMappings.contains(mapping)) {
			return GO_ON;
		}

		// 2.登录校验
		HttpSession session = request.getSession();
		Member member = (Member) session.getAttribute("loginer");
		if (member != null) {
			return GO_ON;
		}
		// 尝试从请求中获取code，进行网页授权登录
		String code = request.getParameter("code");
		if (StringUtil.isNotBlank(code)) {
			Map<String, String> params = Maps.newLinkedHashMap();
			params.put("appid", env.getProperty("weixin.appid"));
			params.put("secret", env.getProperty("weixin.secret"));
			params.put("code", code);
			params.put("grant_type", "authorization_code");
			WebAccessToken webToken = HttpsUtil.get(URLPool.WEB_ACCESS_TOKEN, params, WebAccessToken.class);
			member = memberMapper.findByOpenid(webToken.getOpenid());
			log.info("member = " + member);
			if (member == null) {
				return end(response, UserRespCode.INVALID_TOKEN);
			}
			session.setAttribute("loginer", member);
			return GO_ON;
		}
		return end(response, UserRespCode.INVALID_TOKEN);
	}
}
